<template>

  <el-dialog :title="id ? '  网关通道合集修改' : '  网关通道合集添加'" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false">

    <el-form ref="main-form" :model="form" :rules="rules" :inline="true" >
      <el-form-item label="  网关通道合集名称" size="mini" prop="collectionName">
        <el-input placeholder="" v-model="form.collectionName" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="" size="mini">
        <el-button type="primary" size="mini" @click="handleAddChannel">添加通道</el-button>
      </el-form-item>

      <el-form-item label="支付类型" size="mini" prop="payType">
        <el-select v-model="form.payType" :disabled="id"  size="small" @keyup.enter.native="submit"  clearable>
          <el-option
            v-for="item in payTypeOption"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>


      <div v-for="(channel, key) in form.conn" :key="key">
        <h4>调度通道<el-link type="danger" style="float: right;" @click="form.conn.splice(key, 1)">移除</el-link></h4>
        <el-form-item label="调度级别" size="mini">
          <el-input type="number" placeholder="" v-model="channel.sort" @keyup.enter.native="submit" clearable></el-input>
        </el-form-item>          

        <el-form-item label="选择通道" size="mini">
          <el-select v-model="channel.channelId" size="small" clearable>
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </div>

      <div v-if="id != null">PS:修改  网关通道合集将会影响已关联此  网关通道合集的终端，数字越大优先级越高</div>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close" size="small">取 消</el-button>
      <el-button type="primary" @click="submit" size="small" :loading="loading">提 交</el-button>
    </div>

  </el-dialog>
</template>

<script>

import ApiMain from '@/api/product.info';
import ChannelApiMain from '@/api/bank.channel';

export default {
  mixins: [
  ],
  props: [
  ],
  data () {
    return {

      dialogVisible: false,
      popDeleteVisible: false,
      loading: false,
      isSettingLoad: false,
      payTypeOption:[],
      form: {
        collectionName: '',
        conn: [],
        payType:null,
      },

      rules: {
        collectionName: [
          { required: true, message: '请输入  网关通道合集名称', trigger: 'blur' },
        ],
        payType:[
          { required: true, message: '请选择支付类型', trigger: 'blur' },
        ]
      },

      id  : null,
      data: null,

      channelOptions: []

    }
  },

  mounted () {
    this.fetchChannelOptions()
    this.getPayTypeOption()
  },

  methods: {

    show (id = null) {

      this.id = id;
      if (this.id) {
        this.fetchData();
      }
      else {
        this.reset();
      }

      this.dialogVisible = true;
    },

    close () {
      this.dialogVisible = false;
      this.reset();
      this.$emit('dialog-close');
    },

    reset () {
      this.form = {
        collectionName: '',
        conn: []
      };
    },

    fetchChannelOptions () {
      ChannelApiMain.option().then(re => {
        this.channelOptions = re;
      })
    },
    getPayTypeOption(){
        ChannelApiMain.payOption().then(res=>{
          this.payTypeOption=res
        })
    },
    fetchData () {

      ApiMain.info({id: this.id})
      .then(re => {
        this.data = re; 
      })
      .catch(() => {
        this.data = null;
      })
      .finally(() => {
        this.renderData();
      });
    },

    renderData () {
      this.form=this.data
      this.form.collectionName = this.data.collectionName;
      let conn = [];
      for (var i in this.data.conn) {
        let tmp = {};
        tmp = {
          sort: this.data.conn[i].sort,
          channelId: this.data.conn[i].channelId,
        }
        conn.push(tmp);
      }
      this.form.conn = conn;
      console.log(this.form)
    },

    verifyForm () {
      var bool = true;
      this.$refs['main-form'].validate((valid) => bool = valid);
      return bool;
    },

    async submit () {

      if (! this.verifyForm()) return false;

      let channelIds = [];
      for (var i in this.form.conn) {
        if (!this.form.conn[i].channelId) {
           this.$message({message: '请选择通道', type: 'info'});
          return;
        }
        if (this.form.conn[i].sort == '' || this.form.conn[i].sort < 0) {
           this.$message({message: '通道调度级别应大于等于0', type: 'info'});
          return;
        }
        if (channelIds.indexOf(this.form.conn[i].channelId) >= 0) {
          this.$message({message: '通道不能重复', type: 'info'});
          return;
        }
        channelIds.push(this.form.conn[i].channelId);
      }

      this.loading = true;

      try {
        if (this.id) {
          await this.submitSet();
        }
        else {
          await this.submitAdd();
        }
      } finally {
        this.loading = false;
      }
    },

    async submitDel() {

      this.popDeleteVisible = false;
      this.loading = true;
      try {
        await ApiMain.del({id: this.id});  
      } finally {
        this.loading = false;
      }

      this.close();
      this.$message({message: '删除成功', type: 'success'});
    },

    async submitSet () {

      this.form.id = this.id;
      await ApiMain.set(this.form);
      this.$message({message: '修改成功', type: 'success'});
      this.close();

    },

    async submitAdd () {

      await ApiMain.add(this.form);
      this.$message({message: '添加成功', type: 'success'});
      this.close();
    },

    // 添加调度通道
    handleAddChannel () {
      this.form.conn.push({
        sort: '',
        channelId: '',
      })
    }
  }
}
</script>

<style>

</style>
